#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2022/4/12 10:31
# @Author    :cjw
from os.path import exists
from yaml import safe_load_all, safe_load


class FileBase:
	def __init__(self, file_path: str):
		"""
		:param file_path: 文件路径
		"""
		if not exists(file_path):
			raise FileNotFoundError(f'找不到文件：{file_path}')
		self._file_path = file_path
		self._data = None  # 读取的文件数据


class YmlOperator(FileBase):
	"""yml文件操作"""

	def __init__(self, yml_path: str, multi: bool = False):
		"""
		:param yml_path: yml文件路径
		:param multi: 是否多节读取文件数据，yml文件通过‘---’符号进行多节处理
		"""
		super(YmlOperator, self).__init__(yml_path)
		self._multi = multi

	@property
	def data(self):
		# 第一次获取数据时，才进行读取
		if not self._data:
			with open(self._file_path, encoding='utf-8') as f:
				if self._multi:
					self._data = list(safe_load_all(f))
				else:
					self._data = safe_load(f)
		return self._data


if __name__ == '__main__':
	yml = YmlOperator('../data/calc_add.yml')
	print(yml.data)